package com.kaer.plugin.utils;

import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Environment;

import java.io.File;

import static android.os.Environment.MEDIA_MOUNTED;

public class DirectoryUtils {
	private DirectoryUtils(){};

	
	private static final String EXTERNAL_STORAGE_PERMISSION = "android.permission.WRITE_EXTERNAL_STORAGE";

	/**
	 * 判断是否有内存卡,如果存在则在内存卡中生成目录,否则在默认缓存目录生成.
	 * 
	 * @param context
	 * @param cacheDir
	 * @return File
	 */
	public static File getDirectory(Context context, String cacheDir) {
		File appCacheDir = null;
		if (MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
				&& hasExternalStoragePermission(context)) {
			appCacheDir = new File(Environment.getExternalStorageDirectory(),
					cacheDir);
		}
		if (appCacheDir == null
				|| (!appCacheDir.exists() && !appCacheDir.mkdirs())) {
			appCacheDir = context.getCacheDir();
		}
		return appCacheDir;
	}

	public static File getFile(Context context,String fileName){
		File appCacheDir = null;
		File pathDir=getDirectory(context,"imgCache");

		appCacheDir=new File(pathDir.getPath(),fileName);
		return  appCacheDir;
	}

	private static boolean hasExternalStoragePermission(Context context) {
		int perm = context
				.checkCallingOrSelfPermission(EXTERNAL_STORAGE_PERMISSION);
		return perm == PackageManager.PERMISSION_GRANTED;
	}
}
